#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/types.h>
#include <sys/types.h>
#include <unistd.h>

/**
 * 用于获取用户的FD
 * @param char str[] 输入字符
 * @return int
 */
int getClientFd(char str[200]) {
    int p = 0;
    int value = 0;
    while (str[p] != '\0') {
        if ((str[p] >= '0') && (str[p] <= '9'))
        {
            value = value * 10 + str[p] - '0';
        }
        p++;
    }
    return value;
}


/**
 * 建立socket
 */
void handlerSocket() {
    int socketFd,newFD;
    int res;
    pid_t pid;
    struct sockaddr_in my_address;
    fd_set allFd,copyFd;
    struct sockaddr_in their_address;
    socklen_t socketLength;
    char recvBuf[200],sendBuf[200];
    int recvSize,sendSize;
    int clientFd = NULL;
    // 第一步:创建一个socketFd文件描述符
    socketFd = socket(AF_INET,SOCK_STREAM,0);
    if (socketFd == -1) {
        perror("创建socket出错");
        return;
    }

    // 初始化地址结构体
    my_address.sin_family = AF_INET;
    my_address.sin_port = htons(8811);
    my_address.sin_addr.s_addr = htonl(INADDR_ANY);
    bzero(&my_address.sin_zero, sizeof(my_address));

    // 第二步:进行绑定socketFD到地址

    res = bind(socketFd,(struct sockaddr*)&my_address, sizeof(my_address));
    if (res == -1) {
        perror("绑定socket失败");
        return;
    }

    // 第三步:进行监听socket
    res = listen(socketFd,5);
    if (res == -1) {
        perror("listen失败");
        return;
    }

    // 第四步:进行accept
    socketLength = sizeof(their_address);

    FD_ZERO(&allFd);
    FD_SET(socketFd,&allFd);
    FD_SET(0,&allFd);

    while (1) {
        copyFd = allFd;
        res = select(FD_SETSIZE,&copyFd,NULL,NULL,NULL);
        if (res < 0) {
            perror("select错误");
            return;
        }
        if (res == 0) {
            printf("超时");
        }
        for (int i = 0; i < FD_SETSIZE; ++i) {
            if (FD_ISSET(i,&copyFd)) {
                if (i == socketFd) {
                    newFD = accept(socketFd,(struct sockaddr*)&their_address,&socketLength);
                    FD_SET(newFD,&allFd);
                    printf("新的客户端加入%d",newFD);
                } else if (i == 0) {
                    fgets(sendBuf,200,stdin);
                    clientFd = getClientFd(sendBuf);
                    if (clientFd == 0) {
                        printf("请输入发送的clientFd");
                        memset(sendBuf,0,200);
                    } else {
                        send(clientFd,sendBuf,200,0);
                        memset(sendBuf,0,200);
                    }

                } else {
                    recv(i,recvBuf,200,0);
                    printf("客户端%d:%s\n",i,recvBuf);
                    memset(recvBuf,0,200);
                }
            }
        }
    }

}

int main() {
    handlerSocket();
    return 0;
}

